package com.chzc.fm.duotin.ui.mine;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.bean.mine.UserInfo;
import com.chzc.fm.duotin.ui.other.BaseActivity;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.GlobalParam;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.ImageUtil;
import com.chzc.fm.duotin.utils.Unicode2CN;
import com.chzc.fm.duotin.widget.CircleImageView;
import com.chzc.fm.duotin.widget.TitleBar;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

public class EditInfoActivity extends BaseActivity implements View.OnClickListener{

    private TitleBar titleBar;
    private RelativeLayout rlPhoto;
    private CircleImageView imageAvatar;
    private TextView textMail, textSex, textPwd, textDismiss;
    private EditText editName, editSign;
    private LinearLayout llSex;

    private UserInfo info;

    private final int CAMERA = 0;
    private final int ALBUM = 1;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initViews() {
        titleBar = (TitleBar) findViewById(R.id.title_bar);
        rlPhoto = (RelativeLayout) findViewById(R.id.rl_info_select);
        textMail = (TextView) findViewById(R.id.tv_info_email);
        textSex = (TextView) findViewById(R.id.tv_info_sex);
        textPwd = (TextView) findViewById(R.id.tv_info_pwd);
        textDismiss = (TextView) findViewById(R.id.tv_info_dismiss);
        editName = (EditText) findViewById(R.id.et_info_nick);
        editSign = (EditText) findViewById(R.id.et_info_sign);
        llSex = (LinearLayout) findViewById(R.id.ll_info_sex);
        imageAvatar = (CircleImageView) findViewById(R.id.civ_info_avatar);
    }

    @Override
    protected void initEvents() {
        rlPhoto.setOnClickListener(this);
        textPwd.setOnClickListener(this);
        textDismiss.setOnClickListener(this);
        llSex.setOnClickListener(this);

        titleBar.setLeftListener(new TitleBar.mTitleBarListener() {
            @Override
            public void onClick(View v) {
                exitActivity();
            }
        });
        titleBar.setRightListener(new TitleBar.mTitleBarListener() {
            @Override
            public void onClick(View v) {
                exitActivity();
            }
        });
    }

    @Override
    protected void init() {
        titleBar.setTitleBarVisibility(true, "用户信息");
        titleBar.setRightText("保存");
        titleBar.setLeft(true, R.drawable.arrow_back_white);

        DuotinTask.IRequest request = new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {
                return Unicode2CN.unicode2GBK(HttpUtil.doGet(GlobalParam.INFO_URL).toString());
            }
        };
        DuotinTask.IRequestCallback callBack = new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                try {
                    JSONObject root = new JSONObject(object.toString());
                    String msg = root.getString(GlobalParam.ERROR_MSG);
                    if(GlobalParam.SUCCESS.equals(msg)){
                        JSONObject obj = root.getJSONObject(GlobalParam.DATA);
                        info = UserInfo.objectFromData(obj.toString());
                        initData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String msg) {

            }
        };

        DuotinTask task = new DuotinTask(request, callBack);
        putAsyncTask(task);
    }

    private void initData() {
        textMail.setText(info.getEmail());
        switch (info.getSex()){
            case 0:
                textSex.setText("保密");
                break;
            case 1:
                textSex.setText("男");
                break;
            case 2:
                textSex.setText("女");
                break;
        }
        editName.setText(info.getReal_name());
        editSign.setText(info.getSignature());
        if(info.getImage_url() != "") {
            ImageLoader.getInstance().displayImage(info.getImage_url(), imageAvatar, ImageUtil.getDefaultOptions());
        }
    }

    /**
     * 退出
     */
    private void exitActivity() {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_info_select:
                showPhotoSelect();
                break;
            case R.id.ll_info_sex:
                showChoseSexDia();
                break;
            case R.id.tv_info_pwd:
                startChangePwdActivity();
                break;
            case R.id.tv_info_dismiss:
                exitActivity();
                break;
        }
    }

    private void startChangePwdActivity() {
        Intent i = new Intent(this, ChangePwdActivity.class);
        startActivity(i);
    }

    private void showPhotoSelect() {
        final LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_chose_photo, null);
        final Dialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        dialog.getWindow().setContentView(view);

        TextView textCamera, textAlbum, textCancel;

        textCamera = (TextView) view.findViewById(R.id.tv_photo_camera);
        textAlbum = (TextView) view.findViewById(R.id.tv_photo_album);
        textCancel = (TextView) view.findViewById(R.id.tv_photo_cancel);

        textCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAMERA);

                dialog.dismiss();
            }
        });

        textAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                intent.putExtra("crop", true);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 80);
                intent.putExtra("outputY", 80);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, ALBUM);
                dialog.dismiss();
            }
        });

        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.setCanceledOnTouchOutside(false);
    }

    private void showChoseSexDia() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_chose_sex, null);
        final Dialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        dialog.getWindow().setContentView(view);

        TextView textMan, textWoman, textNull, textCancel;
        textMan = (TextView) view.findViewById(R.id.tv_sex_man);
        textWoman = (TextView) view.findViewById(R.id.tv_sex_woman);
        textNull = (TextView) view.findViewById(R.id.tv_sex_null);
        textCancel = (TextView) view.findViewById(R.id.tv_sex_cancel);

        textMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textSex.setText("男");
                dialog.dismiss();
            }
        });
        textWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textSex.setText("女");
                dialog.dismiss();
            }
        });
        textNull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textSex.setText("保密");
                dialog.dismiss();
            }
        });

        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.setCanceledOnTouchOutside(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CAMERA && resultCode == RESULT_OK && data != null){
            Bitmap bitmap = SaveIntoFile(data);
            imageAvatar.setImageBitmap(bitmap);
        }else if(requestCode == ALBUM && resultCode == RESULT_OK && data != null){
            Bitmap bitmap = SaveIntoFile(data);
            imageAvatar.setImageBitmap(bitmap);
        }

    }

    private Bitmap SaveIntoFile(Intent data) {
        //获取bitmap
        Bundle b = data.getExtras();
        Bitmap bitmap = (Bitmap) b.get("data");
        FileOutputStream fos = null;
        //文件路径
        File dir = FileUtils.DIR_IMAGE;
        //文件名称
        String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        File file = new File(dir, name);

        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);      //把文件写入系统
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try{
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
}
